package com.sy.rabbitmq.new_consumer;

import com.rabbitmq.client.*;
import com.sy.rabbitmq.TestProperties;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 新消费方式 绑定对象
 */
public class Comsumer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 创建ConnectionFactory
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(TestProperties.getIp());
        factory.setPort(TestProperties.getPort());
        factory.setVirtualHost("/");

        //2.获取Connection
        Connection connection = factory.newConnection();

        //3.获取channel
        Channel channel = connection.createChannel();

        //4.通过channel声明一个exchange
        String exchangeName = "test_confirm_exchange";
        String routeKey = "confirm.#";
        String queueName = "test_confirm_queue";
        channel.exchangeDeclare(exchangeName,"topic",true);

        //5.通过channel声明一个队列,绑定设置路由key
        channel.queueDeclare(queueName,true,false,false,null);
        channel.queueBind(queueName,exchangeName,routeKey);

        //---- 老版本编写方式 ----
        //6.创建消费者
//        QueueingConsumer consumer = new QueueingConsumer(channel);
        //7.绑定消费到队列上
//        channel.basicConsume(queueName,true,consumer);
//        while(true){
//            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
//            String msg = new String(delivery.getBody());
//            System.out.println(msg);
//        }

        //---- 新方式直接绑定对象,每次消费过来会调用对象的handleDelivery ----
        channel.basicConsume(queueName,true,new MyConsumer(channel));
    }


    /**
     * 重写消费端
     */
    public static class MyConsumer extends DefaultConsumer {
        /**
         * Constructs a new instance and records its association to the passed-in channel.
         *
         * @param channel the channel to which this consumer is attached
         */
        public MyConsumer(Channel channel) {
            super(channel);
        }


        /**
         * 具体消费代码编写
         * @param consumerTag
         * @param envelope
         * @param properties
         * @param body
         * @throws IOException
         */
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
            System.out.println("-----------------新消费方式-----------------");
            System.out.println("consumerTag"+consumerTag);
            System.out.println("envelope"+envelope);
            System.out.println("AMQP.BasicProperties"+properties);
            System.out.println("body"+new String(body));
        }
    }

}
